<?php

namespace app\admin\controller\business;

//引入进来基类控制器
use app\common\controller\Backend;

/**
 * 客户私海控制器
 */
class Privatesea extends Backend
{
    // 关联查询
    protected $relationSearch = true;
    //当前模型
    protected $model = null;

    //当前无须登录方法
    protected $noNeedLogin = [];

    //无需鉴权的方法,但需要登录
    protected $noNeedRight = [];

    // 快速查询，搜索指定的哪些字段
    protected $searchFields = 'id,nickname,source.name,source.id,admin.id';

    // 地区模型
    protected $RegionModel = null;

    //构造函数
    public function _initialize()
    {
        // 手动继承父级的初始化方法
        parent::_initialize();

        // 加载模型
        $this->model = model('Business.Business');

        $this->ReceiveModel = model('Business.Receive');

        $this->SourceModel = model('Business.Source');

        $this->RegionModel = model('Region');

        $SourceData = $this->SourceModel->column('id,name');

        $SexList = [0 => '保密', 1 => '男', 2 => '女'];
        $DealList = [0 => '未成交', 1 => '已成交'];

        $this->view->assign([
            'SourceData' =>  $SourceData,
            'DealList' => $DealList,
            'SexList' => $SexList,
        ]);
    }

    // 客户私海列表
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 查询总数
            $total = $this->model
                ->with(['source', 'admin'])
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            // 查询数据
            $list = $this->model
                ->with(['source', 'admin'])
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加私有客户
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post('row/a');

            $salt = randstr();

            $password = md5($params['mobile'] . $salt);

            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'email' => $params['email'],
                'deal' => $params['deal'],
                'adminid' => $this->auth->id,
                'password' => $password,
                'salt' => $salt,
                'auth' => $params['auth'],
                'money' => $params['money']
            ];

            // 选择地区
            if (!empty($params['code'])) {

                $parentpath = $this->RegionModel->where('code', $params['code'])->value('parentpath');

                if (!$parentpath) {
                    $this->error('所选的地区不存在，请重新选择');
                }

                $path = explode(',', $parentpath);

                $province = $path[0] ?? null;
                $city = $path[1] ?? null;
                $district = $path[2] ?? null;

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            // 开启事务
            $this->model->startTrans();
            $this->ReceiveModel->startTrans();

            $BusinessStatus = $this->model->validate("common/Business/Business.register")->save($data);

            if ($BusinessStatus === FALSE) {
                $this->error($this->model->getError());
            }

            // 封装领取数据
            $ReceiveData = [
                'applyid' => $this->auth->id,
                'status' => 'allot',
                'busid' => $this->model->id
            ];

            // 插入领取表
            $ReceiveStatus = $this->ReceiveModel->validate('common/Business/Receive')->save($ReceiveData);

            if ($ReceiveStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->ReceiveModel->getError());
            }

            if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
                $this->model->rollback();
                $this->ReceiveModel->rollback();
                $this->error('添加失败');
            } else {
                $this->model->commit();
                $this->ReceiveModel->commit();
                $this->success('添加成功');
            }
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        if (!$row) {
            $this->error(__('未找到当前用户'));
        }

        if ($this->request->isPost()) {

            $params = $this->request->param("row/a");

            $data = [
                'id' =>  $ids,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'deal' => $params['deal'],
                'auth' => $params['auth'],
                'money' => $params['money']
            ];

            if ($params['email'] != $row['email']) {
                $data['auth'] = 0;
            }

            // 修改密码
            if (!empty($params['password'])) {
                $salt = randstr();
                $data['salt'] = $salt;
                $data['password'] = md5($params['password'] . $salt);
            }

            // 修改省市区
            if (!empty($params['code'])) {

                $parentpath = $this->RegionModel->where('code', $params['code'])->value('parentpath');

                if (!$parentpath) {
                    $this->error('所选地区不存在，请重新输入');
                }

                $path = explode(',', $parentpath);

                $province = $path[0] ?? null;
                $city = $path[1] ?? null;
                $district = $path[2] ?? null;

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            $result = $this->model->validate("common/Business/Business.profile")->isUpdate(true)->save($data);

            if ($result === false) {
                $this->error($this->model->getError());
            }

            $this->success();
        }

        // 处理地区数据回显
        $row['regionCode'] = $row['district'] ?: ($row['city'] ?: $row['province']);

        $this->assign([
            "row" => $row
        ]);

        return $this->view->fetch();
    }

    // 回收到公海
    public function recovery($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->model->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('没有找到该用户'));
                exit;
            }
        }
        $ReceiveData = [];
        $businessData = [];
        foreach ($ids as $value) {

            $ReceiveData[] = [
                'applyid' => $this->auth->id,
                'status' => 'recovery',
                'busid' => $value
            ];

            $businessData[] = [
                'id' => $value,
                'adminid' => null
            ];
        }

        $this->model->startTrans();
        $this->ReceiveModel->startTrans();

        // 更新客户表
        $BusinessStatus = $this->model->saveAll($businessData);

        if ($BusinessStatus === FALSE) {
            $this->error($this->model->getError());
        }
        // 插入领取表
        $ReceiveStatus = $this->ReceiveModel->saveAll($ReceiveData);

        if ($ReceiveStatus === FALSE) {
            $this->model->rollback();
            $this->error($this->ReceiveModel->getError());
        }

        if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
            $this->model->rollback();
            $this->ReceiveModel->rollback();
            $this->error('回收失败');
        } else {
            $this->model->commit();
            $this->ReceiveModel->commit();
            $this->success('回收成功');
        }
    }

    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->model->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('没有找到该用户'));
                exit;
            }
        }

        $result = $this->model->destroy($ids);

        if ($result === false) {
            $this->error($this->model->getError());
            exit;
        }

        $this->success('删除成功');
        exit;
    }
}
